package com.rbn.stockmobiledevices.estadisticas;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rbn.stockmobiledevices.entradas.Entrada;
import com.rbn.stockmobiledevices.salidas.Venta;
import com.rbn.stockmobiledevices.utils.AutoCompleteElement;
import com.rbn.stockmobiledevices.utils.ExcelDownloader;

@Controller
public class EstadisticaController {
	
	private static Logger logger = Logger.getLogger(EstadisticaController.class);
	
	private EstadisticaManager estadisticaManager;
	private ExcelDownloader downloader;
	
	@Autowired
	public EstadisticaController(EstadisticaManager estadisticaManager, ExcelDownloader downloader) {
		this.estadisticaManager = estadisticaManager;
		this.downloader = downloader;
	}
	
	@RequestMapping(value="/listStockMinimo", method=RequestMethod.GET)
	public @ResponseBody Map<String, Object> listaStockMinimo(@RequestParam int iDisplayStart, @RequestParam int iDisplayLength, @RequestParam String sEcho) {
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object[]> lista = new ArrayList<Object[]>();
		try{
			lista = estadisticaManager.getStockMinimoList(iDisplayStart, iDisplayLength);
		}catch(Exception e){
			
		}
		map.put("sEcho", sEcho);
		map.put("iTotalRecords", String.valueOf(lista.size()));
		map.put("iTotalDisplayRecords", String.valueOf(lista.size()));
		map.put("lista", lista);
		
		return map;
	}
	
	@RequestMapping(value="/ganancias", method=RequestMethod.GET)
	public @ResponseBody Map<String, Object> getGanancia(@RequestParam int iDisplayStart, @RequestParam int iDisplayLength,
			@RequestParam String sSearch, @RequestParam String sEcho) {
		Calendar cal =  new GregorianCalendar();
		cal.setTime(new Date());
		int agno = cal.get(Calendar.YEAR); 
		if(sSearch!=null && sSearch.length()!=0){
			agno = Integer.valueOf(sSearch);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<Ganancia> ganancias = new ArrayList<Ganancia>();
		try{
			ganancias = estadisticaManager.getGanancia(agno);
		}catch(Exception e){
			
		}
		map.put("sEcho", sEcho);
		map.put("iTotalRecords", String.valueOf(ganancias.size()));
		map.put("iTotalDisplayRecords", String.valueOf(ganancias.size()));
		map.put("ganancias", ganancias);
		
	    return map;
	}
	
	@RequestMapping(value = "/estadisticas", method = RequestMethod.GET)
	public String list(Model model) {
		try{
			List<AutoCompleteElement> lista = estadisticaManager.getAgnos();
			model.addAttribute("lista", lista);
		}catch(Exception e){
		}
		return "estadisticas.tiles";
	}
	
	@RequestMapping(value = "/getTotalCapital", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getTotalCapital() {
		boolean result= true;
		Map<String, Object> map = new HashMap<String, Object>();
		Double total = 0d;
		try{
			total = estadisticaManager.getTotalCapital();
		}catch(Exception e){
			result = false;
		}
		map.put("status", result);
		map.put("value", total);
		return map;
	}
	
	@RequestMapping(value = "/stockMinInd", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getStockMinimoInd() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object[]> lista = new ArrayList<Object[]>();
		try{
			lista = estadisticaManager.getStockMinimoList(null, null);
		}catch(Exception e){
		}
		map.put("stockInd", lista.size()>0);
		return map;
	}
	
	@RequestMapping(value = "/listEntradasImpagas", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getIngresosImpagos(@RequestParam int iDisplayStart, @RequestParam int iDisplayLength, @RequestParam String sEcho) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Entrada> lista = new ArrayList<Entrada>();
		
		try{
			lista = estadisticaManager.getEntradasImpagas(iDisplayStart, iDisplayLength);
		}catch(Exception e){
		}
		
		map.put("sEcho", sEcho);
		map.put("iTotalRecords", String.valueOf(lista.size()));
		map.put("iTotalDisplayRecords", String.valueOf(lista.size()));
		map.put("lista", lista);
		
		return map;
	}
	
	@RequestMapping(value = "/listVentasImpagas", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getVentasImpagas(@RequestParam int iDisplayStart, @RequestParam int iDisplayLength, @RequestParam String sEcho) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Venta> lista = new ArrayList<Venta>();
		
		try{
			lista = estadisticaManager.getVentasImpagas(iDisplayStart, iDisplayLength);
		}catch(Exception e){
		}
		
		map.put("sEcho", sEcho);
		map.put("iTotalRecords", String.valueOf(lista.size()));
		map.put("iTotalDisplayRecords", String.valueOf(lista.size()));
		map.put("lista", lista);
		
		return map;
	}
		
	@RequestMapping(value = "/listStock", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> list(@RequestParam int iDisplayStart, @RequestParam int iDisplayLength, @RequestParam String sEcho,
			@RequestParam(value="sSearch_0") String flt_imei, 
			@RequestParam(value="sSearch_1") String flt_dispositivo, 
			@RequestParam(value="sSearch_2") Long flt_proveedor, 
			@RequestParam(value="sSearch_3") String flt_fecha) {

		flt_imei=flt_imei!=null?flt_imei.trim():"";
		flt_dispositivo=flt_dispositivo!=null?flt_dispositivo.trim():"";
		
		Map<String, Object> map = new HashMap<String, Object>();
		Date fecha = null;
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
		if(flt_fecha!=null && flt_fecha.length()>0){
			try {
				fecha = sdf.parse(flt_fecha);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		List<Stock> stockLst = new ArrayList<Stock>();
		int total = 0;
		int filtered = 0;
		
		try{
			stockLst = estadisticaManager.getAllStock();
			total = stockLst.size();
			filtered = total;
			
			filtered = estadisticaManager.getPaginadoStock(null, null, flt_imei, flt_dispositivo, flt_proveedor, fecha).size();
			stockLst = estadisticaManager.getPaginadoStock(iDisplayStart, iDisplayLength, flt_imei, flt_dispositivo, flt_proveedor, fecha);
		}catch(Exception e){
		}
		
		map.put("sEcho", sEcho);
		map.put("iTotalRecords", String.valueOf(total));
		map.put("iTotalDisplayRecords", String.valueOf(filtered));
		map.put("lista", stockLst);

		return map;
	}
	
	
	@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    public String exportExcel(HttpServletResponse response) {
		logger.info("IN > exportExcel");
	    try {
           downloader.downloadXLS(response);
	    } catch (Exception e) {
            e.printStackTrace();
	    }finally{
	    	logger.info("OUT < exportExcel");
	    }
		return null;
    }
}